package pers.cyril.jdb.protocol.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 文件描述
 *
 * @author yichao wang
 */
public class PacketSpliter extends LengthFieldBasedFrameDecoder {

    private static final int LENGTH_FIELD_OFFSET = 7;
    private static final int LENGTH_FIELD_LENGTH = 4;

    public PacketSpliter() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf obj = (ByteBuf) super.decode(ctx, in);

        int magicNumber = obj.getInt(obj.readerIndex());
        if(magicNumber != PacketCodeC.MAGIC_NUMBER){
            ctx.channel().close();
            return null;
        }
        return obj;
    }
}
